<template>
  <div class="smart-guide">
    <el-row :gutter="20">
      <!-- 左侧常见症状 -->
      <el-col :span="6">
        <el-card class="symptom-card">
          <template #header>
            <div class="card-header">
              <h3>常见症状</h3>
            </div>
          </template>
          <div class="symptom-list">
            <div 
              v-for="category in symptomCategories" 
              :key="category.id"
              class="symptom-category"
            >
              <h4>{{ category.name }}</h4>
              <el-tag
                v-for="symptom in category.symptoms"
                :key="symptom"
                class="symptom-tag"
                @click="addSymptom(symptom)"
                :effect="selectedSymptoms.includes(symptom) ? 'dark' : 'plain'"
              >
                {{ symptom }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 中间诊断区域 -->
      <el-col :span="12">
        <el-card class="guide-card">
          <template #header>
            <div class="card-header">
              <h2>智能导诊</h2>
              <p>AI助手将为您提供专业的就医建议</p>
            </div>
          </template>
          
          <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item prop="symptoms">
              <el-input
                v-model="form.symptoms"
                type="textarea"
                :rows="4"
                :placeholder="inputPlaceholder"
              />
            </el-form-item>
            
            <div class="selected-symptoms" v-if="selectedSymptoms.length">
              <p>已选症状：</p>
              <el-tag
                v-for="symptom in selectedSymptoms"
                :key="symptom"
                closable
                @close="removeSymptom(symptom)"
              >
                {{ symptom }}
              </el-tag>
            </div>
            
            <el-form-item>
              <div class="form-actions">
                <el-button 
                  type="primary" 
                  :loading="loading"
                  @click="handleSubmit"
                >
                  开始诊断
                </el-button>
                <el-button @click="resetForm">重置</el-button>
              </div>
            </el-form-item>
          </el-form>
          
          <div v-if="result" class="result-section">
            <el-divider>诊断结果</el-divider>
            <div v-loading="loading" class="result-content markdown-body" v-html="formattedResult"></div>
            
            <div class="result-actions">
              <el-button type="primary" @click="goToAppointment">
                立即预约
              </el-button>
              <el-button type="success" @click="startChat">
                咨询医生
              </el-button>
              <el-button type="primary" text @click="saveResult">
                保存结果
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧使用指南 -->
      <el-col :span="6">
        <el-card class="help-card">
          <template #header>
            <div class="card-header">
              <h3>使用指南</h3>
            </div>
          </template>
          <div class="help-content">
            <div class="help-item">
              <el-icon><Warning /></el-icon>
              <div class="help-text">
                <h4>注意事项</h4>
                <p>AI诊断建议仅供参考，不能替代医生的专业诊断。如有严重症状，请立即就医。</p>
              </div>
            </div>
            <div class="help-item">
              <el-icon><Document /></el-icon>
              <div class="help-text">
                <h4>使用说明</h4>
                <ol>
                  <li>从左侧选择或直接描述症状</li>
                  <li>尽可能详细描述症状特点</li>
                  <li>提供症状持续时间</li>
                  <li>说明是否有既往病史</li>
                </ol>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getSmartDiagnosis, checkModelConnection } from '@/api/smart_guide'
import { ElMessage } from 'element-plus'
import { Warning, Document } from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
import 'github-markdown-css'

const router = useRouter()
const md = new MarkdownIt()

const formRef = ref(null)
const loading = ref(false)
const result = ref('')
const selectedSymptoms = ref([])
const modelConnected = ref(false)

const form = ref({
  symptoms: ''
})

// 常见症状分类
const symptomCategories = ref([
  {
    id: 1,
    name: '头部症状',
    symptoms: ['头痛', '头晕', '耳鸣', '视力模糊']
  },
  {
    id: 2,
    name: '胸腹症状',
    symptoms: ['胸痛', '腹痛', '恶心', '呕吐', '腹胀']
  },
  {
    id: 3,
    name: '呼吸症状',
    symptoms: ['咳嗽', '气短', '胸闷', '呼吸困难']
  },
  {
    id: 4,
    name: '全身症状',
    symptoms: ['发热', '乏力', '食欲不振', '体重减轻', '失眠']
  }
])

const rules = {
  symptoms: [
    { required: true, message: '请描述您的症状', trigger: 'blur' },
    { min: 10, message: '请详细描述症状(至少10个字)', trigger: 'blur' }
  ]
}

const inputPlaceholder = `请详细描述您的症状，包括：
1. 症状的具体表现
2. 持续时间
3. 是否有既往病史
4. 是否服用过药物
5. 是否有其他不适`

const formattedResult = computed(() => {
  if (!result.value) return ''
  // 先将 <br> 替换为换行符，再进行 Markdown 渲染
  const processedResult = result.value
    .replace(/<br>/g, '\n')
    .replace(/\n\n+/g, '\n\n') // 合并多个连续的换行
  return md.render(processedResult)
})

// 检查大模型连接状态
const checkConnection = async () => {
  try {
    const response = await checkModelConnection()
    modelConnected.value = response.success
    if (response.success) {
      ElMessage.success('大模型连接正常')
    } else {
      ElMessage.warning(`大模型连接异常: ${response.message || '未知错误'}`)
    }
  } catch (error) {
    modelConnected.value = false
    console.error('连接检查失败:', error)
    const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || '未知错误'
    ElMessage.error(`大模型连接失败: ${errorMessage}`)
  }
}

// 在组件挂载时检查连接状态
onMounted(() => {
  checkConnection()
})

// 添加症状
const addSymptom = (symptom) => {
  if (!selectedSymptoms.value.includes(symptom)) {
    selectedSymptoms.value.push(symptom)
    updateSymptomDescription()
  }
}

// 移除症状
const removeSymptom = (symptom) => {
  const index = selectedSymptoms.value.indexOf(symptom)
  if (index > -1) {
    selectedSymptoms.value.splice(index, 1)
    updateSymptomDescription()
  }
}

// 更新症状描述
const updateSymptomDescription = () => {
  if (selectedSymptoms.value.length) {
    form.value.symptoms = `主要症状：${selectedSymptoms.value.join('、')}\n\n${form.value.symptoms}`
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (!modelConnected.value) {
        ElMessage.warning('大模型连接异常，请稍后再试')
        return
      }
      
      loading.value = true
      try {
        console.log('开始发送诊断请求...')
        // 构建发送给大模型的消息
        const messages = [
          {
            role: "system",
            content: "你是一个专业的医疗诊断助手。请根据患者的症状提供专业的诊断建议，包括初步诊断、就医建议、注意事项和健康指导。回答要专业、准确、符合医学规范。"
          },
          {
            role: "user",
            content: `患者症状：${form.value.symptoms}\n\n请按以下格式回复：\n1. 初步诊断\n可能的疾病：\n症状严重程度：\n\n2. 就医建议\n建议就诊科室：\n就医等级：\n就医紧急度：\n\n3. 注意事项\n生活建议：\n饮食建议：\n用药提示：\n\n4. 健康指导\n自我监测：\n预防措施：\n康复建议：`
          }
        ]

        console.log('发送的消息内容:', messages)

        // 发送诊断请求
        const response = await getSmartDiagnosis({
          symptoms: form.value.symptoms,
          messages: messages
        })

        console.log('收到诊断响应:', response)
        console.log('响应状态:', response?.success)
        console.log('响应结果:', response?.result)

        if (response && response.result) {
          // 直接使用返回的结果
          result.value = response.result
          console.log('设置诊断结果成功')
        } else {
          console.error('响应数据不完整:', response)
          throw new Error('未收到有效的诊断结果')
        }
      } catch (error) {
        console.error('诊断请求失败:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response,
          stack: error.stack
        })
        ElMessage.error(error.message || '诊断失败，请稍后重试')
        result.value = '' // 清空结果
      } finally {
        loading.value = false
      }
    }
  })
}

const resetForm = () => {
  formRef.value?.resetFields()
  selectedSymptoms.value = []
  result.value = ''
}

const goToAppointment = () => {
  router.push('/appointments')
}

const startChat = () => {
  router.push('/ai-chat')
}

const saveResult = () => {
  // 实现保存功能
  ElMessage.success('诊断结果已保存')
}
</script>

<style scoped lang="scss">
.smart-guide {
  padding: 20px;
  
  .symptom-card, .help-card {
    height: 100%;
    
    .card-header {
      h3 {
        margin: 0;
        font-size: 18px;
        color: #303133;
      }
    }
  }
  
  .symptom-list {
    .symptom-category {
      margin-bottom: 20px;
      
      h4 {
        margin: 0 0 10px;
        color: #606266;
      }
      
      .symptom-tag {
        margin: 0 8px 8px 0;
        cursor: pointer;
      }
    }
  }
  
  .guide-card {
    .card-header {
      text-align: center;
      
      h2 {
        margin: 0 0 10px;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #909399;
      }
    }
    
    .selected-symptoms {
      margin: 10px 0;
      
      p {
        margin: 0 0 10px;
        color: #606266;
      }
      
      .el-tag {
        margin: 0 8px 8px 0;
      }
    }
    
    .form-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
    }
    
    .result-section {
      margin-top: 30px;
      
      .result-content {
        padding: 20px;
        background: #f5f7fa;
        border-radius: 4px;
        line-height: 1.8;
      }
      
      .result-actions {
        margin-top: 20px;
        display: flex;
        justify-content: center;
        gap: 20px;
      }
    }
  }
  
  .help-card {
    .help-content {
      .help-item {
        display: flex;
        gap: 15px;
        padding: 15px 0;
        border-bottom: 1px solid #ebeef5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .el-icon {
          font-size: 24px;
          color: #e6a23c;
        }
        
        .help-text {
          h4 {
            margin: 0 0 10px;
            color: #303133;
          }
          
          p {
            margin: 0;
            color: #606266;
            line-height: 1.6;
          }
          
          ol {
            margin: 0;
            padding-left: 20px;
            color: #606266;
            
            li {
              margin: 5px 0;
            }
          }
        }
      }
    }
  }
}

:deep(.markdown-body) {
  background: transparent;
  
  table {
    display: table;
    width: 100%;
    margin: 15px 0;
    border-collapse: collapse;
    
    th, td {
      border: 1px solid #dcdfe6;
      padding: 12px;
      text-align: left;
    }
    
    th {
      background: #f5f7fa;
      font-weight: bold;
    }
  }

  h3 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-size: 1.3em;
    font-weight: bold;
  }

  p {
    margin: 16px 0;
    line-height: 1.6;
  }
}
</style> 